# main.py

from pyscript import document
from pyodide.ffi import create_proxy
from roles import ROLES
from game import CardGameApp
from js import alert

class WebUI:
    def __init__(self):
        self.app_container = document.getElementById("app-container")
        self.start_new_game(None)

    def start_new_game(self, event):
        self.game = None
        self.num_players = 0
        self.current_player_index = 0
        self.player_selections = {} 
        self.post_game_skill_queue = []
        self.current_selected_role = list(ROLES.keys())[0]
        self.current_selected_targets = []
        self.render_start_screen()

    # --- 渲染函数 ---
    
    def render_start_screen(self):
        html = """
        <h1 class="title">狂赌之渊同人游戏：STS</h1>
        <p class="subtitle">V1.2 Web版</p>
        <div>
            <p class="start-screen-credits" style="display: inline-block; margin-right: 20px;">Creator：鸽子</p>
            <p class="start-screen-credits" style="display: inline-block; margin-left: 20px;">Programmed by FTP</p>
        </div>
        <hr style="width:50%; border-color:#8B0000; margin: 30px auto;">
        <p>请输入玩家人数:</p>
        <input class="start-screen-input" type="number" id="num-players-input" value="2" min="1">
        <br>
        <button class="start-screen-button" id="start-game-btn" type="button">开始游戏</button>
        """
        self.app_container.innerHTML = html
        document.getElementById("start-game-btn").addEventListener("click", create_proxy(self.start_role_selection_process))

    def render_role_selection(self):
        player_name = f"玩家{self.current_player_index + 1}"
        html = f'<h2 class="role-selection-title">{player_name}，请选择一个角色</h2><div class="role-list">'
        
        unavailable_roles = set(self.player_selections.values())
        if self.current_selected_role in unavailable_roles:
            available_roles = [k for k in ROLES.keys() if k not in unavailable_roles]
            self.current_selected_role = available_roles[0] if available_roles else None

        for role, details in ROLES.items():
            is_disabled = role in unavailable_roles
            selected_class = "selected" if role == self.current_selected_role and not is_disabled else ""
            cursor_style = "cursor: not-allowed; opacity: 0.5;" if is_disabled else "cursor: pointer;"
            
            html += f"""
            <div class="role-item {selected_class}" id="{role}" {"disabled" if is_disabled else ""} style="{cursor_style}">
                <img src="./images/{details.get('image_file', '')}" alt="{role}">
                <div class="role-details"><h3>{role}</h3><p>{details.get('description', '')}</p></div>
            </div>"""

        html += '</div>'
        if self.current_selected_role:
             html += f'<button class="confirm-button" id="confirm-role-btn" type="button">确认选择</button>'
        else:
             html += '<p style="color:red; margin-top:20px;">所有角色已被选择完毕！</p>'
        
        self.app_container.innerHTML = html
        
        for element in document.querySelectorAll(".role-item:not([disabled])"):
            element.addEventListener("click", create_proxy(self.handle_role_click))
        if self.current_selected_role:
            document.getElementById("confirm-role-btn").addEventListener("click", create_proxy(self.handle_role_confirmation))

    def render_game_screen(self):
        if not self.game: return
        if self.game.is_turn_over():
            self.render_turn_summary()
            return
        player = self.game.get_current_player_data()
        card = self.game.get_current_card()
        html = f"""
        <div class="game-header">
            <div class="player-info">
                <img src="./images/{ROLES[player['role']].get('image_file', '')}" alt="{player['role']}">
                <div>
                    <p class="player-name">{player['name']} ({player['role']})</p>
                    <p class="choices-left">剩余选择次数: {player['choices_left']}</p>
                </div>
            </div>
        </div>
        <div class="card-display"><img src="./Cards/{card['image_file']}" alt="{card['rank']}{card['suit']}"></div>
        <div class="choice-buttons">
            <button class="choice-btn take" id="take-btn" type="button">要</button>
            <button class="choice-btn discard" id="discard-btn" type="button">弃牌</button>
        </div>"""
        self.app_container.innerHTML = html
        document.getElementById("take-btn").addEventListener("click", create_proxy(self.handle_make_choice))
        document.getElementById("discard-btn").addEventListener("click", create_proxy(self.handle_make_choice))
    
    def render_turn_summary(self):
        player = self.game.get_current_player_data()
        skill_info = self.game.apply_turn_end_skills(player)
        score = self.game.calculate_turn_score(player)
        def create_card_html(cards):
            if not cards: return "<p>无</p>"
            return ''.join([f'<img class="summary-card" src="./Cards/{card["image_file"]}">' for card in cards])
        html = f"<h1>{player['name']} ({player['role']}) 的回合结束</h1>"
        if player['role'] == '生志摩妄' and player['skill_log']:
            log_html = "<br>".join(player['skill_log'])
            html += f'<div class="summary-section skill-log"><h2>技能结算日志:</h2><p>{log_html}</p></div>'
        if skill_info and skill_info.get("swapped_in"):
            html += f"""
            <div class="summary-section skill-activation"><h2>{player["role"]} 技能发动！</h2>
                <div class="summary-card-row skill-swap">
                    <p>丢弃</p> <img class="summary-card" src="./Cards/{skill_info["swapped_out"]["image_file"]}">
                    <p>换成</p> <img class="summary-card" src="./Cards/{skill_info["swapped_in"]["image_file"]}">
                </div>
            </div>"""
        html += f"""
        <div class="summary-section"><h2>最终选择的牌:</h2><div class="summary-card-row">{create_card_html(player["selected_cards"])}</div></div>
        <div class="summary-section"><h2>弃掉的牌:</h2><div class="summary-card-row">{create_card_html(player["discarded_cards"])}</div></div>
        <h2 class="final-score">本回合总得分: {score}</h2>"""
        if player['role'] == "桃喰绮罗莉" and not player['used_restart']:
            html += '<div class="kirari-choice">'
            html += '<button class="choice-btn discard" id="restart-btn" type="button">重开回合</button>'
            html += '<button class="choice-btn take" id="confirm-turn-btn" type="button">确认回合</button>'
            html += '</div>'
        else:
            button_text = "查看最终结果" if self.game.current_player_index >= self.game.num_players - 1 else "下一位玩家"
            html += f'<button class="confirm-button" id="next-player-btn" type="button">{button_text}</button>'
        self.app_container.innerHTML = html
        if player['role'] == "桃喰绮罗莉" and not player['used_restart']:
            document.getElementById("restart-btn").addEventListener("click", create_proxy(self.handle_restart_turn))
            document.getElementById("confirm-turn-btn").addEventListener("click", create_proxy(self.handle_confirm_turn))
        else:
            document.getElementById("next-player-btn").addEventListener("click", create_proxy(self.handle_next_player))

    def render_target_selection(self, caster_name, num_targets=1):
        caster_data = self.game.players[caster_name]
        targets = [p for p in self.game.players if p != caster_name]
        self.current_selected_targets = []
        html = f'<h2 class="role-selection-title">{caster_name} ({caster_data["role"]})，请选择 {num_targets} 位玩家发动技能：</h2>'
        html += '<div class="role-list">'
        for target_name in targets:
            target_data = self.game.players[target_name]
            # --- 修改开始 ---
            # 获取玩家分数
            score = target_data.get('score', 0)
            # 在显示信息中加入分数
            html += f"""
            <div class="role-item multi-target" id="{target_name}">
                <img src="./images/{ROLES[target_data['role']].get('image_file', '')}" alt="{target_data['role']}">
                <div class="role-details"><h3>{target_name} ({target_data['role']}) - {score}分</h3></div>
            </div>"""
            # --- 修改结束 ---
        html += f'</div><button class="confirm-button" id="confirm-target-btn" type="button">请选择 {num_targets} 位目标</button>'
        self.app_container.innerHTML = html
        for element in document.querySelectorAll(".multi-target"):
            element.addEventListener("click", create_proxy(lambda e: self.handle_multi_target_click(e, num_targets)))
        document.getElementById("confirm-target-btn").addEventListener("click", create_proxy(self.handle_target_confirmation))

    def render_game_results(self):
        sorted_players, penalty_player = self.game.finalize_results()
        if penalty_player:
            alert(f"{penalty_player}（下月売奥理）未进入前两名，需要接受惩罚！")
        html = '<h1>游戏结束！最终排名</h1><table class="results-table">'
        html += '<thead><tr><th>排名</th><th>玩家</th><th>角色</th><th>总得分</th></tr></thead><tbody>'
        for i, (name, data) in enumerate(sorted_players):
            rank_class = "rank-1" if i == 0 else ""
            penalty_class = "penalty" if name == penalty_player else ""
            html += f'<tr class="{penalty_class}"><td class="{rank_class}">{i + 1}</td><td class="{rank_class}">{name}</td><td><img src="./images/{ROLES[data["role"]].get("image_file", "")}" class="result-avatar"> {data["role"]}</td><td class="{rank_class}">{data["score"]}</td></tr>'
        html += '</tbody></table><button class="restart-button" id="restart-game-btn" type="button">重新开始</button>'
        self.app_container.innerHTML = html
        document.getElementById("restart-game-btn").addEventListener("click", create_proxy(self.start_new_game))

    # --- 事件处理函数 ---

    def start_role_selection_process(self, event):
        try:
            num = int(document.getElementById("num-players-input").value)
            if num < 1: raise ValueError()
            if num > len(ROLES):
                alert(f"玩家人数({num})不能超过角色总数({len(ROLES)})！")
                return
            self.num_players = num
            self.current_player_index = 0
            self.player_selections = {}
            self.current_selected_role = list(ROLES.keys())[0]
            self.render_role_selection()
        except (ValueError, TypeError):
            alert("请输入一个有效的正整数作为玩家人数！")

    def handle_role_click(self, event):
        role_id = event.currentTarget.id
        self.current_selected_role = role_id
        for item in document.querySelectorAll(".role-item"): item.classList.remove("selected")
        document.getElementById(self.current_selected_role).classList.add("selected")

    def handle_role_confirmation(self, event):
        if not self.current_selected_role:
            alert("请选择一个可用的角色！")
            return
        player_name = f"玩家{self.current_player_index + 1}"
        self.player_selections[player_name] = self.current_selected_role
        self.current_player_index += 1
        if self.current_player_index < self.num_players:
            unavailable_roles = set(self.player_selections.values())
            available_roles = [k for k in ROLES.keys() if k not in unavailable_roles]
            self.current_selected_role = available_roles[0] if available_roles else None
            self.render_role_selection()
        else:
            self.start_actual_game()

    def start_actual_game(self):
        self.game = CardGameApp(self.player_selections)
        self.game.start_game()
        for player in self.game.players.values():
            if player['role'] == "下月売奥理":
                card_text = ", ".join([f"{c['suit']}{c['rank']}" for c in player['cards']])
                alert(f"{player['name']} (下月売奥理) 技能发动！\n你的6张牌是: {card_text}")
        self.render_game_screen()

    def handle_make_choice(self, event):
        self.game.make_choice(event.target.id == "take-btn")
        self.render_game_screen()

    def handle_restart_turn(self, event):
        self.game.restart_turn()
        self.render_game_screen()

    def handle_confirm_turn(self, event):
        self.handle_next_player(event)

    def handle_next_player(self, event):
        self.game.advance_to_next_player()
        if self.game.is_game_over():
            self.post_game_skill_queue = self.game.get_post_game_skill_players()
            self.process_post_game_skills()
        else:
            self.render_game_screen()
            
    def process_post_game_skills(self):
        if self.post_game_skill_queue:
            caster_name = self.post_game_skill_queue[0]
            caster_role = self.game.players[caster_name]['role']
            skill_effect = ROLES[caster_role].get("skill_effect", {})
            num_targets = skill_effect.get("num_targets", 1)
            self.render_target_selection(caster_name, num_targets)
        else:
            self.render_game_results()

    def handle_multi_target_click(self, event, max_targets):
        target_element = event.currentTarget
        target_id = target_element.id
        if target_id in self.current_selected_targets:
            self.current_selected_targets.remove(target_id)
            target_element.classList.remove("selected")
        else:
            if len(self.current_selected_targets) < max_targets:
                self.current_selected_targets.append(target_id)
                target_element.classList.add("selected")
        confirm_btn = document.getElementById("confirm-target-btn")
        if len(self.current_selected_targets) == max_targets:
            confirm_btn.innerText = "确认目标"
        else:
            confirm_btn.innerText = f"请选择 {max_targets} 位目标 ({len(self.current_selected_targets)}/{max_targets})"
        
    def handle_target_confirmation(self, event):
        caster = self.post_game_skill_queue[0]
        caster_role = self.game.players[caster]['role']
        skill_effect = ROLES[caster_role].get("skill_effect", {})
        num_targets = skill_effect.get("num_targets", 1)
        if len(self.current_selected_targets) != num_targets:
            alert(f"您必须选择 {num_targets} 位目标！")
            return
        self.post_game_skill_queue.pop(0)
        message = self.game.apply_post_game_skill(caster, self.current_selected_targets)
        alert(message)
        self.process_post_game_skills()

WebUI()